import { View, Text, Image } from '@tarojs/components'
import { cloud, navigateTo } from '@tarojs/taro'
import CloudIcons from '@/assets/ImageUrlConfig'
import './index.scss'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { GetSpaceApi } from '@/api/index'

export default function DrawerSpaceList({ show, setShow, setIsShowInputPopoverForFullSpaceName }) {
	const dispatch = useDispatch()
	const userStore = useSelector((state) => state.user)
	const spaceStore = useSelector((state) => state.space)

	let timer
	const Amination_Timer = 200
	const [isShowMask, setIsShowMask] = useState(false)
	const [drawerClassName, setDrawerClassName] = useState('change-space-drawer')

	useEffect(() => {
		clearTimeout(timer)
		if (show) {
			setIsShowMask(true)
			timer = setTimeout(() => {
				setDrawerClassName('change-space-drawer load')
			}, Amination_Timer)
			return
		}
		setDrawerClassName('change-space-drawer')
		timer = setTimeout(() => {
			setIsShowMask(false)
		}, Amination_Timer)
	}, [show])

	const updateCurrentUsingSpace = (id) => {
		GetSpaceApi({ id })
			.then((data) => {
				dispatch({
					type: 'UPDATE_SPACE',
					payload: data,
				})
			})
			.catch((err) => {
				throw err
			})
	}

	return (
		<View
			className={isShowMask ? 'mask' : 'mask hiden'}
			onTap={() => {
				setShow(false)
			}}
		>
			<View
				className={drawerClassName}
				onTap={(e) => {
					e.stopPropagation()
				}}
			>
				<View className='user'>
					<View className='left'>
						<View className='avatar'>
							<Image src={userStore.avatar} className='img'></Image>
						</View>
						<Text className='nickname'>{userStore.nickname}</Text>
					</View>
					<View
						className='setting'
						onTap={() => {
							navigateTo({
								url: '/pages/setting/index',
							})
						}}
					>
						<Image src={CloudIcons.setting} className='img'></Image>
					</View>
				</View>

				<View className='title'>
					<Text>我的空间</Text>
					<View
						className='add'
						onTap={() => {
							setIsShowInputPopoverForFullSpaceName(true)
						}}
					>
						<Image src={CloudIcons.add2} className='img'></Image>
					</View>
				</View>

				<View className='space-list'>
					{userStore.space?.map((space) => {
						return (
							<View
								className='space-item'
								onTap={() => {
									space._id !== spaceStore._id && updateCurrentUsingSpace(space._id)
								}}
							>
								<Text className='name'>{space.name}</Text>
								{spaceStore?._id === space._id ? <Image src={CloudIcons.gou} className='img'></Image> : null}
							</View>
						)
					})}
				</View>
			</View>
		</View>
	)
}
